'use client';
import dynamic from 'next/dynamic';
import {useCallback, useState} from 'react';
import Button from 'react-bootstrap/Button';
import Stack from 'react-bootstrap/Stack';
import Loading from '@/app/loading';
import useDebounce from '@/components/hook/useDebounce';
import useTrans from '@/modules/i18nTranslation';
import beautifyJson from '@/utils/beautifyJson';
import style from './style.module.scss';

const CodeMirrorItem = dynamic(
    () => import('./CodeMirror'),
    {ssr: false, loading: () => <Loading></Loading>}
);

const Home = () => {
    const {t} = useTrans();
    const [value, setValue] = useState('{}');
    const debounce = useDebounce(800);

    const handleFormat = useCallback(() => {
        const val = beautifyJson(value);
        setValue(val);
    }, [value]);

    const handleCompress = () => {
        const val = JSON.stringify(value, null, '');
        setValue(val);
    };

    const handleEscape = useCallback(() => {
        setValue(encodeURIComponent(value));
    }, [value]);

    const handleChange = useCallback((val: string) => {
        debounce(() => setValue(val));
    }, [debounce]);

    return <Stack gap={2} className={style['json-editor-root-wrapper']}>
        <div className={style['code-wrapper']}>
            <CodeMirrorItem {...{value, onChange: handleChange}}></CodeMirrorItem>
        </div>
        <Stack direction='horizontal' gap={2}>
            <Button style={{minWidth: 80}} onClick={handleFormat}>{t('格式化')}</Button>
            <Button style={{minWidth: 80}} onClick={handleCompress}>{t('压缩')}</Button>
            <Button style={{minWidth: 80}} onClick={handleEscape}>{t('转义')}</Button>
        </Stack>
    </Stack>;
};

export default Home;
